package com.daxiong.json.servlet.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "QueryServlet", urlPatterns = { "/query" }, loadOnStartup = 1)
public class QueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	final String URL = "http://data.gcis.nat.gov.tw/od/data/api/6BBA2268-1367-4B42-9CCA-BC17499EBE8C?$format=json&$filter=Company_Name like %s and Company_Status eq 01";

	@Override
	protected void doGet( //
			final HttpServletRequest httpServletRequest, //
			final HttpServletResponse httpServletResponse //
	) throws ServletException, IOException {
		final String companyName = //
		httpServletRequest.getParameter("companyName");

		final String json = readJsonFromUrl(companyName);

		httpServletResponse.setContentType("text/x-json;charset=UTF-8");
		httpServletResponse.setHeader("Cache-Control", "no-cache");
		httpServletResponse.getWriter().print(json);
	}

	private String readJsonFromUrl( //
			final String companyName //
	) throws MalformedURLException, IOException {
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		final StringBuilder json = new StringBuilder();
		try {
			final URL url = new URL(String.format(URL, companyName));
			final Charset charset = Charset.forName("UTF-8");
			inputStream = url.openStream();
			inputStreamReader = new InputStreamReader(inputStream, charset);
			bufferedReader = new BufferedReader(inputStreamReader);
			int info;
			while ((info = bufferedReader.read()) != -1) {
				json.append((char) info);
			}
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (inputStreamReader != null) {
				inputStreamReader.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return json.toString();
	}
}
